package xuegao.study.mall.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xuegao.study.mall.repo.dao.oms.OmsOrderSettingDao;
import xuegao.study.mall.repo.dao.sms.SmsCouponHistoryDao;
import xuegao.study.mall.common.dto.OmsOrderDetail;
import xuegao.study.mall.common.model.oms.OmsOrderSetting;
import xuegao.study.mall.common.model.sms.SmsCouponHistory;
import xuegao.study.mall.web.component.CancelOrderSender;
import xuegao.study.mall.web.domain.CartPromotionItem;
import xuegao.study.mall.web.domain.ConfirmOrderResult;
import xuegao.study.mall.web.domain.OrderParam;
import xuegao.study.mall.web.service.*;
import xuegao.study.mall.common.api.CommonPage;
import xuegao.study.mall.repo.dao.oms.OmsOrderDao;
import xuegao.study.mall.repo.dao.oms.OmsOrderItemDao;
import xuegao.study.mall.repo.dao.pms.PmsSkuStockDao;
import xuegao.study.mall.repo.dao.ums.UmsIntegrationConsumeSettingDao;
import xuegao.study.mall.common.domain.portal.SmsCouponHistoryDetail;
import xuegao.study.mall.common.exception.Assert;
import xuegao.study.mall.common.model.oms.OmsOrder;
import xuegao.study.mall.common.model.oms.OmsOrderItem;
import xuegao.study.mall.common.model.pms.PmsSkuStock;
import xuegao.study.mall.common.model.sms.SmsCoupon;
import xuegao.study.mall.common.model.sms.SmsCouponProductCategoryRelation;
import xuegao.study.mall.common.model.sms.SmsCouponProductRelation;
import xuegao.study.mall.common.model.ums.UmsIntegrationConsumeSetting;
import xuegao.study.mall.common.model.ums.UmsMember;
import xuegao.study.mall.common.model.ums.UmsMemberReceiveAddress;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PortalOrderServiceImpl implements PortalOrderService {
    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private OmsCarItemService omsCarItemService;

    @Autowired
    private UmsMemberReceiveAddressService umsMemberReceiveAddressService;

    @Autowired
    private PmsSkuStockDao pmsSkuStockDao;

    @Autowired
    private OmsOrderDao omsOrderDao;

    @Autowired
    private OmsOrderItemDao omsOrderItemDao;

    @Autowired
    private UmsMemberCouponService umsMemberCouponService;

    @Autowired
    private UmsIntegrationConsumeSettingDao umsIntegrationConsumeSettingDao;

    @Autowired
    private OmsOrderSettingDao omsOrderSettingDao;

    @Autowired
    private CancelOrderSender cancelOrderSender;

    @Autowired
    private SmsCouponHistoryDao smsCouponHistoryDao;

    @Override
    public ConfirmOrderResult generateConfirmOrder(List<Long> cartIds) {
        ConfirmOrderResult result = new ConfirmOrderResult();
        UmsMember currentMember = umsMemberService.getCurrentMember();
        Long memberId = currentMember.getId();
        // 1.获取购物车信息
        List<CartPromotionItem> cartPromotionItemList = omsCarItemService.listPromotion(memberId, cartIds);
        result.setCartPromotionItemList(cartPromotionItemList);
        // 2.获取用户收获地址列表
        List<UmsMemberReceiveAddress> memberReceiveAddressList = umsMemberReceiveAddressService.list();
        result.setMemberReceiveAddressList(memberReceiveAddressList);
        // 3.获取用户可用优惠卷列表
        List<SmsCouponHistoryDetail> couponHistoryDetailList = umsMemberCouponService.listCart(cartPromotionItemList, 1);
        result.setCouponHistoryDetailList(couponHistoryDetailList);
        // 4.获取用户积分
        result.setMemberIntegration(currentMember.getIntegration());
        // 5.获取积分使用规则

        // 6.计算总金额,活动优惠,应付金额
        ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList);
        result.setCalcAmount(calcAmount);
        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> generateOrder(OrderParam param) {
        List<OmsOrderItem> orderItemList = new ArrayList<>();
        // 获取购物车及优惠卷信息
        UmsMember currentMember = umsMemberService.getCurrentMember();
        Long memberId = currentMember.getId();
        List<CartPromotionItem> cartPromotionItemList = omsCarItemService.listPromotion(memberId, param.getCartIds());
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            // 生成下单商品信息
            OmsOrderItem orderItem = new OmsOrderItem();
            orderItem.setProductId(cartPromotionItem.getProductId());
            orderItem.setProductName(cartPromotionItem.getProductName());
            orderItem.setProductPic(cartPromotionItem.getProductPic());
            orderItem.setProductAttr(cartPromotionItem.getProductAttr());
            orderItem.setProductBrand(cartPromotionItem.getProductBrand());
            orderItem.setProductSn(cartPromotionItem.getProductSn());
            orderItem.setProductPrice(cartPromotionItem.getPrice());
            orderItem.setProductQuantity(cartPromotionItem.getQuantity());
            orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());
            orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());
            orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());
            orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());
            orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());
            orderItem.setGiftIntegration(cartPromotionItem.getIntegration());
            orderItem.setGiftGrowth(cartPromotionItem.getGrowth());
            orderItemList.add(orderItem);
        }
        // 判断购物车中商品是否都有库存
        if (!hasStock(cartPromotionItemList)) {
            Assert.fail("库存不足,无法下单");
        }
        // 判断是否使用了优惠卷
        if (param.getCouponId() == null) {
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setCouponAmount(new BigDecimal(0));
            }
        } else {
            // 使用优惠卷
            SmsCouponHistoryDetail couponHistoryDetail = getUserCoupon(cartPromotionItemList, param.getCouponId());
            if (couponHistoryDetail == null) {
                Assert.fail("该优惠卷不可用");
            }
            // 对下单商品的优惠卷进行处理
            handleCouponAmount(orderItemList, couponHistoryDetail);
        }
        // 判断是否使用积分
        if (param.getUseIntegration() == null || param.getUseIntegration().equals(0)) {
            // 不使用积分
            for (OmsOrderItem orderItem : orderItemList) {
                orderItem.setIntegrationAmount(new BigDecimal(0));
            }
        } else {
            // 使用积分
            BigDecimal totalAmount = calcTotalAmount(orderItemList);
            BigDecimal integrationAmount = getUseIntegrationAmount(param.getUseIntegration(), totalAmount, currentMember, param.getCouponId() != null);
            if (integrationAmount.compareTo(new BigDecimal(0)) == 0) {
                Assert.fail("积分不可用");
            } else {
                // 可用情况下分摊到可用商品中
                for (OmsOrderItem orderItem : orderItemList) {
                    BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(integrationAmount);
                    orderItem.setIntegrationAmount(perAmount);
                }
            }
        }
        // 计算order_item实付金额
        handleRealAmount(orderItemList);
        // 进行库存锁定
        lockStock(cartPromotionItemList);
        // 根据商品合计,运费,活动优惠,优惠卷,积分计算应付金额
        OmsOrder order = new OmsOrder();
        order.setDiscountAmount(new BigDecimal(0));
        order.setTotalAmount(calcTotalAmount(orderItemList));
        order.setFreightAmount(new BigDecimal(0));
        order.setPromotionAmount(calcPromotionAmount(orderItemList));
        order.setPromotionInfo(getOrderPromotionInfo(orderItemList));
        if (order.getCouponId() == null) {
            order.setCouponAmount(new BigDecimal(0));
        } else {
            order.setCouponId(param.getCouponId());
            order.setCouponAmount(calcCouponAmount(orderItemList));
        }
        if (order.getUseIntegration() == null) {
            order.setIntegration(0);
            order.setIntegrationAmount(new BigDecimal(0));
        } else {
            order.setIntegration(param.getUseIntegration());
            order.setIntegrationAmount(calcIntegrationAmount(orderItemList));
        }
        order.setPayAmount(calcPayAmount(order));
        // 转化为订单信息并插入到数据库
        order.setMemberId(currentMember.getId());
        order.setCreateTime(new Date());
        order.setMemberUsername(currentMember.getUsername());
        // 支付方式: 0->未支付 1->支付宝 2->微信
        order.setPayType(param.getPayType());
        // 订单来源:0->PC订单 1->app订单
        order.setSourceType(1);
        // 订单状态 0->待付款 1->代发货 2->已发货 3->已完成 4->已关闭 5->无效订单
        order.setStatus(0);
        // 订单类型 0->正常订单 1->秒杀订单
        order.setOrderType(0);
        // 收货人信息:姓名 电话 邮编 地址
        UmsMemberReceiveAddress address = umsMemberReceiveAddressService.getItem(param.getMemberReceiveAddressId());
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getPhoneNumber());
        order.setReceiverPostCode(address.getPostCode());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverRegion(address.getRegion());
        order.setReceiverDetailAddress(address.getDetailAddress());
        // 0->未确认 1->已确认
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        // 计算赠送积分
        order.setIntegration(calcGiftIntegration(orderItemList));
        // 计算成长值
        order.setGrowth(calcGiftGrowth(orderItemList));
        // 生成订单号
        order.setOrderSn(generateOrderSn(order));
        // 设置自动收货天数(todo 先写死)
        order.setAutoConfirmDay(1);
        // 插入order表和order_item表
        omsOrderDao.insert(order);
        for(OmsOrderItem orderItem : orderItemList) {
            orderItem.setOrderId(order.getId());
            orderItem.setOrderSn(order.getOrderSn());
            omsOrderItemDao.insert(orderItem);
        }
        // 删除购物车中的商品
        deleteCartItemList(cartPromotionItemList, currentMember);
        // 发送延迟消息取消订单
        sendDelayMessageCancelOrder(order.getId());
        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("orderItemList", orderItemList);
        return result;
    }



    /**
     * 获取用户可用积分抵扣金额
     * @param useIntegration 使用分积分数量
     * @param totalAmount  订单总金额
     * @param currentMember 使用的用户
     * @param hasCoupon 是否已经使用优惠卷
     * @return
     */
    private BigDecimal getUseIntegrationAmount(Integer useIntegration, BigDecimal totalAmount, UmsMember currentMember, boolean hasCoupon) {
        BigDecimal zeroAmount = new BigDecimal(0);
        // 判断用户是否有这么多积分
        if (useIntegration.compareTo(currentMember.getIntegration()) > 0) {
            return zeroAmount;
        }
        // 根据积分使用规则判断是否可用
        UmsIntegrationConsumeSetting integrationConsumeSetting = umsIntegrationConsumeSettingDao.selectById(1);
        if (hasCoupon && integrationConsumeSetting.getCouponStatus().equals(0)) {
            // 不可与优惠卷同时使用
            return zeroAmount;
        }
        // 是否达到最低使用积分门槛
        if (useIntegration.compareTo(integrationConsumeSetting.getUseUnit()) < 0) {
            return zeroAmount;
        }
        // 是否超过订单抵用最高百分比
        BigDecimal integrationAmount = new BigDecimal(useIntegration).divide(new BigDecimal(integrationConsumeSetting.getUseUnit()), 2, RoundingMode.HALF_EVEN);
        BigDecimal maxPercent = new BigDecimal(integrationConsumeSetting.getMaxPercentPerOrder()).divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN);
        if (integrationAmount.compareTo(totalAmount.multiply(maxPercent)) > 0) {
            return zeroAmount;
        }
        return integrationAmount;
    }

    /**
     * 对优惠卷优惠进行处理
     * @param orderItemList order_item列表
     * @param couponHistoryDetail 可用优惠卷详情
     */
    private void handleCouponAmount(List<OmsOrderItem> orderItemList, SmsCouponHistoryDetail couponHistoryDetail) {
        SmsCoupon coupon = couponHistoryDetail.getCoupon();
        if (coupon.getUseType().equals(0)) {//全场通用
            calcPerCouponAmount(orderItemList, coupon);
        } else if (coupon.getUseType().equals(1)) {//指定分类
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 0);
            calcPerCouponAmount(couponOrderItemList, coupon);
        } else if (coupon.getUseType().equals(2)) {//指定商品
            List<OmsOrderItem> couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, 1);
            calcPerCouponAmount(couponOrderItemList, coupon);
        }
    }

    /**
     *
     * @param couponHistoryDetail 优惠卷详情
     * @param orderItemList order_item列表
     * @param type 0:指定分类 1:指定商品
     * @return
     */
    private List<OmsOrderItem> getCouponOrderItemByRelation(SmsCouponHistoryDetail couponHistoryDetail, List<OmsOrderItem> orderItemList, int type) {
        List<OmsOrderItem> resultList = new ArrayList<>();
        if (type == 0) {
            List<Long> categoryIdList = new ArrayList<>();
            List<SmsCouponProductCategoryRelation> categoryRelationList = couponHistoryDetail.getCategoryRelationList();
            for (SmsCouponProductCategoryRelation categoryRelation : categoryRelationList) {
                categoryIdList.add(categoryRelation.getProductCategoryId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (categoryIdList.contains(orderItem.getProductCategoryId())) {
                    resultList.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        } else if (type == 1) {
            List<Long> productIdList = new ArrayList<>();
            List<SmsCouponProductRelation> productRelationList = couponHistoryDetail.getProductRelationList();
            for (SmsCouponProductRelation productRelation : productRelationList) {
                productIdList.add(productRelation.getProductId());
            }
            for (OmsOrderItem orderItem : orderItemList) {
                if (productIdList.contains(orderItem.getProductId())) {
                    resultList.add(orderItem);
                } else {
                    orderItem.setCouponAmount(new BigDecimal(0));
                }
            }
        }
        return resultList;
    }

    /**
     * 对每个下单商品进行优惠卷金额分摊的计算
     * @param orderItemList 可用优惠卷的下单商品
     * @param coupon 优惠卷
     */
    private void calcPerCouponAmount(List<OmsOrderItem> orderItemList, SmsCoupon coupon) {
        BigDecimal totalAmount = calcTotalAmount(orderItemList);
        for(OmsOrderItem orderItem : orderItemList) {
            //(商品价格/可用商品总价)*优惠卷面额
            BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(coupon.getAmount());
            orderItem.setCouponAmount(couponAmount);
        }
    }

    /**
     * 获取该用户可以使用的优惠卷
     * @param cartPromotionItemList 购物车中的优惠卷列表
     * @param couponId 优惠卷id
     * @return 用户可用的优惠卷
     */
    private SmsCouponHistoryDetail getUserCoupon(List<CartPromotionItem> cartPromotionItemList, Long couponId) {
        List<SmsCouponHistoryDetail> couponHistoryDetailList = umsMemberCouponService.listCart(cartPromotionItemList, 1);
        for (SmsCouponHistoryDetail couponHistoryDetail : couponHistoryDetailList) {
            if (couponHistoryDetail.getCoupon().getId().equals(couponId)) {
                return couponHistoryDetail;
            }
        }
        return null;
    }

    @Override
    public OmsOrderDetail detail(Long orderId) {
        OmsOrder omsOrder = omsOrderDao.selectById(orderId);
        Map<String, Object> params = new HashMap<>();
        params.put("order_id", omsOrder.getId());
        List<OmsOrderItem> orderItemList = omsOrderItemDao.selectByMap(params);
        OmsOrderDetail omsOrderDetail = new OmsOrderDetail();
        BeanUtils.copyProperties(omsOrder, omsOrderDetail);
        omsOrderDetail.setOrderItemList(orderItemList);
        return omsOrderDetail;
    }

    @Override
    @Transactional
    public Integer paySuccess(Long orderId, Integer payType) {
        // 1.修改订单状态
        OmsOrder order = new OmsOrder();
        order.setId(orderId);
        order.setStatus(1);// 状态-代发货
        order.setPaymentTime(new Date());
        order.setPayType(payType);
        omsOrderDao.updateByPrimaryKey(order);
        // 2.恢复所有下单商品的锁定库存,扣减真实库存
        xuegao.study.mall.common.dto.OmsOrderDetail detail = omsOrderDao.getDetail(orderId);
        int count = omsOrderDao.updateSkuStock(detail.getOrderItemList());
        return count;
    }

    @Override
    @Transactional
    public void paySuccessByOrderSn(String orderSn, Integer payType) {
        // todo
    }

    @Override
    public CommonPage<OmsOrderDetail> list(Integer status, Integer pageNum, Integer pageSize) {
        if (status == -1) {
            status = null;
        }
        UmsMember currentMember = umsMemberService.getCurrentMember();
        PageHelper.startPage(pageNum, pageSize);
        Map<String, Object> orderParams = new HashMap<>();
        orderParams.put("delete_status", 0);
        orderParams.put("member_id", currentMember.getId());
        if (status != null) {
            orderParams.put("status", status);
        }
        List<OmsOrder> orderList = omsOrderDao.selectByMap(orderParams);
        CommonPage<OmsOrder> orderPage = CommonPage.restPage(orderList);
        // 设置分页信息
        CommonPage<OmsOrderDetail> resultPage = new CommonPage<>();
        resultPage.setPageNum(orderPage.getPageNum());
        resultPage.setPageSize(orderPage.getPageSize());
        resultPage.setTotal(orderPage.getTotal());
        resultPage.setTotalPage(orderPage.getTotalPage());
        if (CollUtil.isEmpty(orderList)) {
            return resultPage;
        }
        // 设置数据信息
        Map<String, Object> orderItemParams = new HashMap<>();
        List<OmsOrderDetail> orderDetailList = new ArrayList<>();
        for (OmsOrder omsOrder : orderList) {
            OmsOrderDetail omsOrderDetail = new OmsOrderDetail();
            BeanUtils.copyProperties(omsOrder, omsOrderDetail);
            orderItemParams.put("order_id", omsOrder.getId());
            List<OmsOrderItem> realtedItemList = omsOrderItemDao.selectByMap(orderItemParams);
            omsOrderDetail.setOrderItemList(realtedItemList);
            orderDetailList.add(omsOrderDetail);
        }
        resultPage.setList(orderDetailList);
        return resultPage;
    }

    @Override
    @Transactional
    public Integer cancelTimeOutOrder() {
        Integer count = 0;
        OmsOrderSetting omsOrderSetting = omsOrderSettingDao.selectById(1L);
        // 查询超时,未支付的订单及订单详情
        List<OmsOrderDetail> timeOutOrders = omsOrderDao.getTimeOutOrders(omsOrderSetting.getNormalOrderOvertime());
        if (CollUtil.isEmpty(timeOutOrders)) {
            return count;
        }
        // 修改订单状态为交易取消
        List<Long> ids = timeOutOrders.stream().map(OmsOrder::getId).collect(Collectors.toList());
        omsOrderDao.updateOrderStatus(ids, 4);
        for (OmsOrderDetail timeOutOrder : timeOutOrders) {
            // 解除订单商品库存锁定
            omsOrderDao.releaseSkuStockLock(timeOutOrder.getOrderItemList());
            // 修改优惠卷使用状态
            updateCouponStatus(timeOutOrder.getCouponId(), timeOutOrder.getMemberId(), 0);
            // 返还使用积分
            if (timeOutOrder.getUseIntegration() != null) {
                UmsMember umsMember = umsMemberService.getById(timeOutOrder.getMemberId());
                int allIntegration = umsMember.getIntegration() + timeOutOrder.getUseIntegration();
                umsMemberService.updateIntegration(timeOutOrder.getMemberId(), allIntegration);
            }
        }
        return timeOutOrders.size();
    }

    @Override
    @Transactional
    public void cancelOrder(Long orderId) {
        // 1.先查询该订单
        Map<String, Object> orderParams = new HashMap<>();
        orderParams.put("id",  orderId);
        orderParams.put("status", 0);
        orderParams.put("delete_status", 0);
        List<OmsOrder> omsOrders = omsOrderDao.selectByMap(orderParams);
        if (CollUtil.isEmpty(omsOrders)) {
            return;
        }
        OmsOrder cancelOrder = omsOrders.get(0);
        if (cancelOrder != null) {
            // 修改订单状态为取消
            List<Long> ids = new ArrayList<>();
            ids.add(cancelOrder.getId());
            omsOrderDao.updateOrderStatus(ids, 4);
            // 查询订单详情,释放库存
            Map<String, Object> orderItemParams = new HashMap<>();
            orderItemParams.put("order_id", cancelOrder.getId());
            List<OmsOrderItem> orderItemList = omsOrderItemDao.selectByMap(orderItemParams);
            if (!CollUtil.isEmpty(orderItemList)) {
                // 解除订单商品库存锁定
                omsOrderDao.releaseSkuStockLock(orderItemList);
            }
            // 修改优惠卷状态
            updateCouponStatus(cancelOrder.getCouponId(), cancelOrder.getMemberId(), 0);
            // 返还积分
            if (cancelOrder.getUseIntegration() != null) {
                UmsMember umsMember = umsMemberService.getById(cancelOrder.getMemberId());
                int allIntegration = umsMember.getIntegration() + cancelOrder.getUseIntegration();
                umsMemberService.updateIntegration(cancelOrder.getMemberId(), allIntegration);
            }
        }
    }

    /**
     * 将优惠卷信息更改为指定状态
     * @param couponId 优惠卷id
     * @param memberId 会员id
     * @param useStatus 使用状态 0->未使用  1->已使用
     */
    private void updateCouponStatus(Long couponId, Long memberId, Integer useStatus) {
        if (couponId == null) {
            return;
        }
        // 查询第一张优惠卷
        Map<String, Object> params = new HashMap<>();
        params.put("coupon_id", couponId);
        params.put("member_id", memberId);
        params.put("use_status", useStatus == 0 ? 1 : 0);
        List<SmsCouponHistory> couponHistoryList = smsCouponHistoryDao.selectByMap(params);
        if (!CollUtil.isEmpty(couponHistoryList)) {
            SmsCouponHistory couponHistory = couponHistoryList.get(0);
            couponHistory.setUseTime(new Date());
            couponHistory.setUseStatus(useStatus);
            smsCouponHistoryDao.updateById(couponHistory);
        }
    }

    @Override
    @Transactional
    public void sendDelayMessageCancelOrder(Long id) {
        // 获取订单超时时间
        OmsOrderSetting omsOrderSetting = omsOrderSettingDao.selectById(1L);
        // 将分钟转换为毫秒
        long delayTimes = omsOrderSetting.getNormalOrderOvertime() * 60 * 1000;
        // 发送延迟消息
        cancelOrderSender.sendMessage(id, delayTimes);
    }

    @Override
    @Transactional
    public void confirmReceiveOrder(Long orderId) {
        UmsMember member = umsMemberService.getCurrentMember();
        OmsOrder order = omsOrderDao.selectById(orderId);
        if (!member.getId().equals(order.getMemberId())) {
            Assert.fail("不能确认他人订单");
        }
        if (!order.getStatus().equals(2)) {
            Assert.fail("订单还未发货");
        }
        order.setStatus(3);
        order.setConfirmStatus(1);
        order.setReceiveTime(new Date());
        omsOrderDao.updateByPrimaryKey(order);
    }

    @Override
    @Transactional
    public void deleteOrder(Long orderId) {
        UmsMember member = umsMemberService.getCurrentMember();
        OmsOrder order = omsOrderDao.selectById(orderId);
        if (!member.getId().equals(order.getMemberId())) {
            Assert.fail("不能删除他人订单");
        }
        if (order.getStatus() == 3 || order.getStatus() == 4) {
            order.setStatus(1);
            omsOrderDao.updateByPrimaryKey(order);
        } else {
            Assert.fail("只能删除已完成或已关闭的订单");
        }
    }

    private void deleteCartItemList(List<CartPromotionItem> cartPromotionItemList, UmsMember currentMember) {
        List<Long> ids = new ArrayList<>();
        for(CartPromotionItem item : cartPromotionItemList) {
            ids.add(item.getId());
        }
        omsCarItemService.delete(currentMember.getId(), ids);
    }

    /**
     * 生成订单编号
     */
    private String generateOrderSn(OmsOrder order) {
        StringBuilder sb = new StringBuilder();
        sb.append("XG");
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        sb.append(date);
        long timeStamp = System.currentTimeMillis();
        sb.append(timeStamp);
        return sb.toString();
    }

    /**
     * 计算订单赠送的成长值
     * @param orderItemList
     * @return
     */
    private Integer calcGiftGrowth(List<OmsOrderItem> orderItemList) {
        Integer sum = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum = sum + orderItem.getGiftGrowth() * orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 计算订单赠送的积分
     * @param orderItemList
     * @return
     */
    private Integer calcGiftIntegration(List<OmsOrderItem> orderItemList) {
        Integer sum  = 0;
        for (OmsOrderItem orderItem : orderItemList) {
            sum += orderItem.getGiftIntegration() * orderItem.getProductQuantity();
        }
        return sum;
    }

    /**
     * 计算订单应付金额
     * @param order
     * @return
     */
    private BigDecimal calcPayAmount(OmsOrder order) {
        // 总金额+运费-促销优惠-优惠卷优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getPromotionAmount())
                .subtract(order.getCouponAmount())
                .subtract(order.getIntegrationAmount());
        return payAmount;
    }

    /**
     * 计算订单积分优惠金额
     * @param orderItemList
     * @return
     */
    private BigDecimal calcIntegrationAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal integrationAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getIntegrationAmount() != null) {
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return integrationAmount;
    }

    /**
     * 计算订单优惠卷金额
     * @param orderItemList
     * @return
     */
    private BigDecimal calcCouponAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return couponAmount;
    }

    /**
     * 计算订单促销优惠金额
     * @param orderItemList
     * @return
     */
    private BigDecimal calcPromotionAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for(OmsOrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return promotionAmount;
    }

    /**
     * 获取订单促销信息
     * @param orderItemList
     * @return
     */
    private String getOrderPromotionInfo(List<OmsOrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for(OmsOrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(";");
        }
        String result = sb.toString();
        if (result.endsWith(";")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }

    /**
     * 计算总金额
     * @param orderItemList
     * @return
     */
    private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OmsOrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }

    private void handleRealAmount(List<OmsOrderItem> orderItemList) {
        for (OmsOrderItem orderItem : orderItemList) {
            // 原价-促销优惠-优惠卷抵扣-积分抵扣
            BigDecimal realAmount = orderItem.getProductPrice()
                    .subtract(orderItem.getPromotionAmount())
                    .subtract(orderItem.getCouponAmount())
                    .subtract(orderItem.getIntegrationAmount());
            orderItem.setRealAmount(realAmount);
        }
    }

    /**
     * 锁定库存
     * @param cartPromotionItemList
     */
    private void lockStock(List<CartPromotionItem> cartPromotionItemList) {
        for(CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            PmsSkuStock skuStock = pmsSkuStockDao.selectById(cartPromotionItem.getProductSkuId());
            skuStock.setLockStock(skuStock.getLockStock() + cartPromotionItem.getQuantity());
            pmsSkuStockDao.updateById(skuStock);
        }
    }

    /**
     * 判断下单商品是否都有库存
     */
    private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) {
        for (CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            if (cartPromotionItem.getRealStock() == null || //判断真实库存是否为空
                    cartPromotionItem.getRealStock() <= 0 || //判断真实库存是否小于0
                    cartPromotionItem.getRealStock() < cartPromotionItem.getQuantity()) {//判断真实库存是否小于下单的数量
                return false;
            }
        }
        return true;
    }

    private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList) {
        ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount();
        calcAmount.setFreightAmount(new BigDecimal(0));// 总运费
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal promotionAmount = new BigDecimal("0");
        for(CartPromotionItem cartPromotionItem : cartPromotionItemList) {
            totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
            promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity())));
        }
        calcAmount.setTotalAmount(totalAmount);// 总金额
        calcAmount.setPromotionAmount(promotionAmount);//活动优惠金额
        calcAmount.setPayAmount(totalAmount.subtract(promotionAmount));// 应付的金额
        return calcAmount;
    }
}
